package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.utils.CaptchaUtil;
import com.example.lotterysystem.common.utils.MailUtil;
import com.example.lotterysystem.common.utils.RedisUtil;
import com.example.lotterysystem.common.utils.RegexUtil;
import com.example.lotterysystem.service.VerificationCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 获取 和 发送 验证码操作
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    private static final Logger logger = LoggerFactory.getLogger(VerificationCodeServiceImpl.class);

    // 为了区分业务，应该给key定义前缀，对于 Redis 里面的 key 需要标准化

    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_"; // 前缀
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L; // 过期时间

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MailUtil mailUtil;

    /**
     * 往 email 邮箱中发送验证码
     * @param email
     */
    @Override
    public void sendVerificationCode(String email) {
        // 检验 邮箱是否正确
        if (!RegexUtil.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        // 生成随机的验证码
        String code = CaptchaUtil.getCaptcha(4);
        // 发送验证码
        String subject = "登录验证码";
        String context = "您的登录验证码是: " + code + "，1分钟内有效";
        mailUtil.sendSampleMail(email,subject,context);
        // 缓存到 Redis 中
        redisUtil.set(VERIFICATION_CODE_PREFIX + email,code,VERIFICATION_CODE_TIMEOUT);
    }

    /**
     * 获取验证码
     * @param email
     * @return
     */
    @Override
    public String getVerificationCode(String email) {
        // 检验 邮箱是否正确
        if (!RegexUtil.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX + email);
    }
}
